//获取应用实例
let app = getApp();

let FormCheckRule = {
	areaAddressNullMessage:"请填写完整的地址信息",
	checkService:"请阅读并同意《国内特快专递承诺服务免责条款》"
};

Page({
	data: {
		imgUrls: '',
		isShowImg: false,
		userName: '', //地址信息
		postalCode: '',
		provinceName: '',
		cityName: '',
		countyName: '',
		detailInfo: '',
		nationalCode: '',
		telNumber: '',

		sendTypeName: '普通快递', //寄送类型
		sendType: 1,
		isShowSendTypeList: false, 
		sendTypeData: [   //取证方式
			{times: 1, timesName: "普通快递",},
			{times: 2, timesName: "香港快递"}
		],

		goodsTypeName: '文件',
		goodsType: '01',
		isShowGoodsTypeList: false, 
		goodsData: [
			{times: '01', timesName: "文件",},
			{times: '02', timesName: "数码产品"},
			{times: '03', timesName: "生活用品",},
			{times: '04', timesName: "校园包裹"},
			{times: '05', timesName: "其他物品",}
		],
		needInvoice: 1,  //是否勾选
    	isCanScroll: true, //屏幕是否能够滑动
		isShowFootNav: true,  //底部导航菜单
		isShowModal: false,
		num: 0  //订单数
	},

	//获得广告图片
	getAdvertisement() {
		let that = this;
		let advertOpt = {   //请求广告
			url: app.globalData.host + "/wx/sd/ad.ajax",
			data: {},
			sucFn: function (result) {
				let imgUrls = result.body;
				if(imgUrls.icon){
					that.setData({
						imgUrls: imgUrls.icon,
						isShowImg: true
					})
				}else {
					that.setData({
						imgUrls: imgUrls,
						isShowImg: false
					})
				}
			}
		};
		app.ajax(advertOpt);
	},

	/**
	 * 获的原生地址信息
	 */
	getChooseAddress() {
		let that = this;
		if(wx.chooseAddress){
			wx.chooseAddress({
				success: (res)=> {
					that.setData({
						userName: res.userName,
						postalCode: res.postalCode,
						provinceName: res.provinceName,
						cityName: res.cityName,
						countyName: res.countyName,
						detailInfo: res.detailInfo,
						nationalCode: res.nationalCode,
						telNumber: res.telNumber
					})
					let page = app.setStorageSync(app.globalData.cacheData,Object.assign({},this.data,
						{ popErrorMsg: '' },{errorFocusName:''}));
				},
				fail: (err)=>{ //用户取消授权获取地址信息，弹出弹框是否进入设置页设置
					if(that.data.isShowModal){ //当用户取消授权后不弹出重新抽取弹框，当再次点击地址弹此框
						wx.showModal({
							title: '',
							content: '需要打开小程序的设置重新授权获取您的揽件地址',
							confirmText: '去设置',
							confirmColor: '#00B488',
							success: function(res) {
								if (res.confirm) { //用户点击确定
									wx.openSetting({	
										success: (res) => {						 
											res.authSetting = {
											  "scope.address": true
											}
										}
									})
								} else if (res.cancel) {
									console.log('用户点击取消')
								}
							}
						});
					}else{
						that.setData({
							isShowModal: true
						})
					}
				},
			})
		}else{
			console.log('当前微信版本不支持chooseAddress');
		}
	},
	
	//是否勾选协议
	checkTap(e) {
		let needInvoice = e.target.dataset.agree;
		if(needInvoice==0){
			needInvoice = 1;
		}else{
			needInvoice = 0;
		}
		this.setData({needInvoice: needInvoice});
	},

	//分享功能
	onShareAppMessage() {
		return {
			title: 'EMS寄快递办理',
			desc: 'EMS寄快递办理',
			path: '/pages/handle/handle'
		}
	},

	onLoad(options) {
		app.globalData.channelId = decodeURIComponent(options.scene) != 'undefined'?
								decodeURIComponent(options.scene) : app.globalData.channelId ? 
								app.globalData.channelId:'';
		console.log("channelId",app.globalData.channelId);
	},

	onShow(options) {
		let that = this;
		app.getOrderNum(function (num,openId){
			let page = app.getStorageSync(app.globalData.cacheData);
			that.setData(Object.assign({},page,{num: num}));
			that.getAdvertisement()  //广告
		})
	},

	//底部切换页面方法
	toUrl(e) {
		let url = e.currentTarget.dataset.url;
		if(url!='/pages/handle/handle'){
			app.setStorageSync(app.globalData.cacheData,this.data);
			if(url == ''){
				//develop（开发版），trial（体验版），release（正式版）
				let res = {
					appid: app.globalData.appid,
					path: '',
					envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			}else {
				app.redirectTo({url: url})
			}
		}
	},

	cacheData() {
		app.setStorageSync(app.globalData.cacheData,Object.assign({},this.data,{ popErrorMsg: '' },{errorScrollIntoViewName: ''},
			{errorFocusName:''}, {isCanScroll: true},{isShowModal: false})); //保存状态在缓存
	},

	onHide() {
		this.cacheData()
	},

	//确认提交按钮
	formSubmit(e){
		let {sendType,userName,goodsType,telNumber,detailInfo,provinceName,cityName,countyName,nationalCode,needInvoice} = this.data;
		let flag = app.check([
			{
				value: userName,
				fn: (value) => {
					if(value == ''){
						app.errorToast(FormCheckRule.areaAddressNullMessage);
						return false;
					}else {
						return true;
					}
				}
			},{
				value: needInvoice,
				fn: (value)=> {
					if(value == ''){
						app.errorToast(FormCheckRule.checkService);
						return false;
					}else {
						return true;
					}
				}
			},
		]);
		if (!flag) {
			return false;
		}

		if(!app.globalData.isAuthSuccess){
            app.toastAuthFailModal();
            return false;
		}
		
		let platform = '';
		if(app.isAndroid()){
		   platform = 'android'
        }else{
			platform = 'iPhone'
		}
		
		let formResult = {
			"payType": 0,//到付
			'platform': platform,
			'formId': e.detail.formId,
			"mailingAddressRange": sendType,
			"postUserName": userName,
			"goodType": goodsType,
			"channelId": "wx",
			"address.provinceId": nationalCode.substr(0,2) + '0000',
			"address.cityId": nationalCode.substr(0,4) + '00',
			"address.countyId": nationalCode,
			"address.contactName": userName,
			"address.cellNum": telNumber,
			"address.street": detailInfo,
			"address.fullAddr": provinceName + cityName + countyName + detailInfo 
		};
		let {sendTypeName,goodsTypeName} = this.data;
		let opt = {
			url: app.globalData.host+"/wx/sd/handling.ajax",
			data: formResult,
			sucFn: (result) =>{
				let orderId = result.body.orderIds[0].id;
				formResult['orderId'] = orderId
				formResult['sendTypeName'] = sendTypeName
				formResult['goodsTypeName'] = goodsTypeName 
				formResult['timeDiffer'] = result.body.timeDiffer
				app.setStorageSync(app.globalData.cacheOrderPay, formResult);
				app.navigateTo({url:'../payment/payment?orderId=' + orderId})
			}
		};
		app.ajax(opt);
	},

	//说明内容
	agreeTap(e) {
		let isNoticeShow='';
		switch (this.data.sendType){
			case 1:
				isNoticeShow = 'ordinary'
				break;
			case 2:
				isNoticeShow = 'hk'
				break;
		}
		app.navigateTo({url:'../agreement/agreement?isNoticeShow='+ isNoticeShow})
	},

	//点击邮寄类型显示类别列表
	sendTypeSelection(e) {
		this.setData({
			isCanScroll:false,
			isShowSendTypeList: true,
			isShowFootNav: false
		});
	},

  //点击mask隐藏旅游邮寄类别列表
	hideSendTypeSelection() {
		this.setData({
			isCanScroll: true,
			isShowSendTypeList: false,
			isShowFootNav: true
		});
	},

	//选择邮寄类型
	selectSendType(e) {
		this.setData({
			sendType: e.target.dataset.type,
			sendTypeName: e.target.dataset.name
		})
	},

	//取消按钮
	cancelSendTypeSelection() {
		this.setData({
			sendType: -1,
			isCanScroll: true,
			isShowSendTypeList: false,
			isShowFootNav: true,
		});
	},

	//start
	//点击商品类型显示类别列表
	goodsTypeSelection(e) {
		this.setData({
			isCanScroll:false,
			isShowGoodsTypeList: true,
			isShowFootNav: false
		})
	},

  //点击mask隐藏旅游邮寄类别列表
	hideGoodsTypeSelection() {
		this.setData({
			isCanScroll: true,
			isShowGoodsTypeList: false,
			isShowFootNav: true
		});
	},

	//选择邮寄类型
	selectGoodsType(e) {
		this.setData({
			goodsType: e.target.dataset.type,
			goodsTypeName: e.target.dataset.name
		})
	},

	//取消按钮
	cancelGoodsTypeSelection() {
		this.setData({
			sendType: -1,
			isCanScroll: true,
			isShowGoodsTypeList: false,
			isShowFootNav: true,
		});
	}
	//end
});
